<!--
 * @Description: 菜单管理-关联接口
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-09-26
-->
<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, reactive, watch } from 'vue'

  import { requestInterfaceList } from '/@/api/system/ysys-user/interface'
  import { requestGetPermissionInterfaces, requestSavePermissionInterfaces } from '/@/api/system/ysys-user/permission'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const props = defineProps({
    visible: { type: Boolean, default: false },
    permissionId: { type: Number, default: NaN },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal) => {
      if (newVal) onPageshow()
      else onPageHide()
    },
  )

  /**
   * 页面显示
   */
  const onPageshow = () => initData()

  /**
   * 页面关闭
   */
  const onPageHide = () => {}

  /** 接口列表 */
  const interfaceList = reactive({
    datas: [],
    expandedKeys: [],
    checkedKeys: [],
  })

  /**
   * 初始化数据
   */
  const initData = async () => {
    // 初始化接口列表
    const { responseData: interfaceData } = await requestInterfaceList({})
    interfaceList.datas = convertTreeData(interfaceData)
    interfaceList.expandedKeys = interfaceData.map((item) => item.permissionId)
    // 选中拥有权限的接口
    const { responseData: permissionData } = await requestGetPermissionInterfaces({ permissionId: props.permissionId })
    interfaceList.checkedKeys = permissionData
  }

  /**
   * 转换树节点数据
   * @param treeNodes 树节点
   */
  const convertTreeData = (treeNodes: InterfaceListTypes.IResponse[]) => {
    return treeNodes.map((item) => {
      const { interfaceName, interfaceId, children } = item
      return { title: interfaceName, key: interfaceId, children: convertTreeData(children) }
    })
  }

  /**
   * 确定
   */
  const onOk = async () => {
    const { responseCode } = await requestSavePermissionInterfaces({ permissionId: props.permissionId, interfaceIds: interfaceList.checkedKeys.checked })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('操作成功')
      visible.value = false
      emits('success')
    }
  }
</script>

<template>
  <div class="interface-relate">
    <a-modal v-model:visible="visible" title="关联接口" @ok="onOk()">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-tree :tree-data="interfaceList.datas" v-model:expandedKeys="interfaceList.expandedKeys" v-model:checkedKeys="interfaceList.checkedKeys" checkable :checkStrictly="true" :selectable="false">
          <template #title="{ title }">{{ title }}</template>
        </a-tree>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped></style>
